package com.ilop.sthome.mvp.present.mine;

import android.content.Context;
import android.os.Handler;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.aliyun.iot.aep.sdk.apiclient.callback.IoTResponse;
import com.aliyun.iot.aep.sdk.credential.IotCredentialManager.IoTCredentialListener;
import com.aliyun.iot.aep.sdk.credential.IotCredentialManager.IoTCredentialManageError;
import com.aliyun.iot.aep.sdk.credential.IotCredentialManager.IoTCredentialManageImpl;
import com.aliyun.iot.aep.sdk.credential.data.IoTCredentialData;
import com.aliyun.iot.aep.sdk.login.LoginBusiness;
import com.aliyun.iot.aep.sdk.login.data.UserInfo;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.app.MyApplication;
import com.ilop.sthome.data.greenDao.UserInfoBean;
import com.ilop.sthome.mvp.contract.mine.MainContract;
import com.ilop.sthome.mvp.contract.mine.PersonalContract;
import com.ilop.sthome.mvp.model.PersonalModel;
import com.example.common.mvp.onModelCallBack;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.ui.fragment.device.DeviceFragment;
import com.ilop.sthome.ui.fragment.message.MessageFragment;
import com.ilop.sthome.ui.fragment.scene.SceneFragment;
import com.ilop.sthome.utils.greenDao.utils.UserInfoDaoUtil;
import com.siterwell.familywellplus.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author skygge
 * @Date on 2019-09-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：主页面业务逻辑
 */
public class MainPresenter extends BasePresenterImpl<MainContract.IView> implements MainContract.IPresent {

    private Context mContext;
    private PersonalContract.IModel mModel;
    private Handler mHandler;

    public MainPresenter(Context mContext) {
        this.mContext = mContext;
        mHandler = new Handler();
        mModel = new PersonalModel(mHandler);
    }

    @Override
    public List<Fragment> getFragmentList() {
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new DeviceFragment());
        fragmentList.add(new SceneFragment());
        fragmentList.add(new MessageFragment());
        return fragmentList;
    }

    @Override
    public void refreshRequestUserInfo() {
        IoTCredentialManageImpl ioTCredentialManage = IoTCredentialManageImpl.getInstance(MyApplication.getInstance());
        if (null == ioTCredentialManage) {
            return;
        }
        if (TextUtils.isEmpty(ioTCredentialManage.getIoTToken())) {
            ioTCredentialManage.asyncRefreshIoTCredential(new IoTCredentialListener() {
                @Override
                public void onRefreshIoTCredentialSuccess(IoTCredentialData ioTCredentialData) {
                    onQueryUserInfo(ioTCredentialData.identity);
                }

                @Override
                public void onRefreshIoTCredentialFailed(IoTCredentialManageError ioTCredentialManageError) {
                    mView.loginOut();
                }
            });
        } else {
            onQueryUserInfo(ioTCredentialManage.getIoTIdentity());
        }
    }

    @Override
    public void onQueryUserInfo(String identifyId) {
        mModel.toQueryUserInfo(identifyId, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() ==200) {
                    try {
                        Object data = response.getData();
                        List<UserInfoBean> userList = JSON.parseArray(data.toString(), UserInfoBean.class);
                        if (userList.size() > 0) {
                            UserInfoDaoUtil.getInstance().toUpdateUser(userList);
                            getUserInfo(userList.get(0));
                        }else {
                            getUserInfo(null);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    getUserInfo(null);
                }
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    @Override
    public void getUserInfo(UserInfoBean userInfoBean) {
        if (userInfoBean == null) {
            userInfoBean = UserInfoDaoUtil.getInstance().findCurrentUser();
        }
        UserInfoBean finalUserInfoBean = userInfoBean;
        mHandler.post(()->{
            mView.showLoginName(getLoginName());
            mView.showNickName(finalUserInfoBean.getNickName());
            mView.showUserImage(finalUserInfoBean.getAvatarUrl());
        });
    }

    @Override
    public void onLoginOut() {
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                mView.loginOut();
            }

            @Override
            public void onCancel() {
            }
        });
        mDialog.setTitleAndButton(mContext.getString(R.string.ali_current_account) + ":" + getLoginName(), mContext.getString(R.string.cancel), mContext.getString(R.string.logout));
        mDialog.show();
    }

    private String getLoginName() {
        if (LoginBusiness.isLogin()) {
            UserInfo userInfo = LoginBusiness.getUserInfo();
            String userName = "";
            if (userInfo != null) {
                if (!TextUtils.isEmpty(userInfo.userPhone)) {
                    userName = userInfo.userPhone;
                } else if (!TextUtils.isEmpty(userInfo.userEmail)) {
                    userName = userInfo.userEmail;
                } else {
                    userName = "";
                }
            }
            return userName;
        }
        return null;
    }
}
